package com.YHVision.qiuzhike.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.constant.CommonConstant;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.mapper.JobPostingMapper;
import com.YHVision.qiuzhike.model.dto.jobPosting.JobPostingQueryRequest;
import com.YHVision.qiuzhike.model.entity.JobPosting;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.JobPostingVO;
import com.YHVision.qiuzhike.model.vo.UserVO;
import com.YHVision.qiuzhike.service.JobPostingService;
import com.YHVision.qiuzhike.service.UserService;
import com.YHVision.qiuzhike.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企业招聘服务实现
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@Service
@Slf4j
public class JobPostingServiceImpl extends ServiceImpl<JobPostingMapper, JobPosting> implements JobPostingService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param jobPosting
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validJobPosting(JobPosting jobPosting, boolean add) {
        ThrowUtils.throwIf(jobPosting == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String jobTitle = jobPosting.getJobTitle();
        String jobDescription = jobPosting.getJobDescription();
        String location = jobPosting.getLocation();
        String requirements = jobPosting.getRequirements();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(jobTitle), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(jobDescription), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(location), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(StringUtils.isBlank(requirements), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(jobTitle)) {
            ThrowUtils.throwIf(jobTitle.length() > 30, ErrorCode.PARAMS_ERROR, "职位名称过长");

        }
        if (StringUtils.isNotBlank(jobDescription)) {
            ThrowUtils.throwIf(jobDescription.length() > 1024, ErrorCode.PARAMS_ERROR,"职位描述过长");

        }
        if (StringUtils.isNotBlank(location)) {
            ThrowUtils.throwIf(location.length() > 100, ErrorCode.PARAMS_ERROR," 工作地点描述过长");
        }
        if (StringUtils.isNotBlank(requirements)) {
            ThrowUtils.throwIf(requirements.length() > 1024, ErrorCode.PARAMS_ERROR," 职位要求描述过长");
        }
    }

    /**
     * 获取查询条件
     *
     * @param jobPostingQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<JobPosting> getQueryWrapper(JobPostingQueryRequest jobPostingQueryRequest) {
        QueryWrapper<JobPosting> queryWrapper = new QueryWrapper<>();
        if (jobPostingQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = jobPostingQueryRequest.getId();
        Long notId = jobPostingQueryRequest.getNotId();
        String sortField = jobPostingQueryRequest.getSortField();
        String sortOrder = jobPostingQueryRequest.getSortOrder();
        String jobTitle = jobPostingQueryRequest.getJobTitle();
        String jobDescription = jobPostingQueryRequest.getJobDescription();
        String salaryRange = jobPostingQueryRequest.getSalaryRange();
        String location = jobPostingQueryRequest.getLocation();
        String requirements = jobPostingQueryRequest.getRequirements();

        Long userId = jobPostingQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(jobTitle), "jobTitle", jobTitle);
        queryWrapper.like(StringUtils.isNotBlank(jobTitle), "jobDescription", jobDescription);
        queryWrapper.like(StringUtils.isNotBlank(requirements), "requirements", requirements);
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(salaryRange), "salaryRange", salaryRange);
        queryWrapper.eq(ObjectUtils.isNotEmpty(location), "location", location);

        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取企业招聘封装
     *
     * @param jobPosting
     * @param request
     * @return
     */
    @Override
    public JobPostingVO getJobPostingVO(JobPosting jobPosting, HttpServletRequest request) {
        // 对象转封装类
        JobPostingVO jobPostingVO = JobPostingVO.objToVo(jobPosting);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = jobPosting.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        jobPostingVO.setUser(userVO);
        // endregion

        return jobPostingVO;
    }

    /**
     * 分页获取企业招聘封装
     *
     * @param jobPostingPage
     * @param request
     * @return
     */
    @Override
    public Page<JobPostingVO> getJobPostingVOPage(Page<JobPosting> jobPostingPage, HttpServletRequest request) {
        List<JobPosting> jobPostingList = jobPostingPage.getRecords();
        Page<JobPostingVO> jobPostingVOPage = new Page<>(jobPostingPage.getCurrent(), jobPostingPage.getSize(), jobPostingPage.getTotal());
        if (CollUtil.isEmpty(jobPostingList)) {
            return jobPostingVOPage;
        }
        // 对象列表 => 封装对象列表
        List<JobPostingVO> jobPostingVOList = jobPostingList.stream().map(jobPosting -> {
            return JobPostingVO.objToVo(jobPosting);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = jobPostingList.stream().map(JobPosting::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        jobPostingVOList.forEach(jobPostingVO -> {
            Long userId = jobPostingVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            jobPostingVO.setUser(userService.getUserVO(user));
        });
        // endregion

        jobPostingVOPage.setRecords(jobPostingVOList);
        return jobPostingVOPage;
    }

}
